/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.desktop.ui.dialog.security;

import kz.kstu.ent.app.context.AppContext;
import kz.kstu.ent.app.delegate.api.AccountDelegate;
import kz.kstu.ent.app.delegate.impl.AccountDelegateImpl;
import kz.kstu.ent.business.entity.security.Account;
import kz.kstu.ent.desktop.images.GUIFactory;
import kz.kstu.ent.desktop.images.GUIIcon;
import kz.kstu.ent.desktop.ui.ControllerLife;
import kz.kstu.ent.desktop.util.GUIUtils;
import kz.kstu.ent.util.StringUtil;
import org.apache.log4j.Logger;
import org.jasypt.util.password.BasicPasswordEncryptor;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.LoginException;
import javax.swing.*;
import java.awt.event.*;

public class ChangePasswordDialog extends JDialog implements ControllerLife {

    public static final Logger LOGGER = Logger.getLogger(LoginDialog.class);

    private static final String TITLE = "Технический лицей :: Смена пароля";

    private static final int WIDTH = 400;
    private static final int HEIGHT = 220;

    private static final String PASSWORDS_NOT_MATCH = "Введенные пароли не совпадают";
    private static final String EMPTY_PASSWORD = "Пароль не может быть пустым";
    private static final String PASSWORD_SUCCESSFULLY_CHANGED = "Пароль успешно изменен";
    private static final String INCORRECT_LOGIN_OR_PASSWORD = "Логин и/или пароль указан неверно";
    private static final String LOGIN_NOT_FOUND = "Указанный логин не найден";

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JPasswordField oldPasswordField;
    private JPasswordField confirmNewPasswordField;
    private JPasswordField newPasswordField;

    public ChangePasswordDialog() {
        initIcons();
        initStaticComponents();
    }

    public void changePassword() {
    }

    private void initIcons() {
        setIconImage(
                GUIFactory.getImage(GUIIcon.KEY)
        );
        buttonOK.setIcon(
                GUIFactory.getIcon(GUIIcon.OK)
        );
        buttonCancel.setIcon(
                GUIFactory.getIcon(GUIIcon.CANCEL)
        );
    }

    public void initStaticComponents() {
        setContentPane(contentPane);
        setModal(true);
        setResizable(false);
        setTitle(TITLE);
        setSize(WIDTH, HEIGHT);
        initListeners();
        getRootPane().setDefaultButton(buttonOK);
        GUIUtils.centerAndShow(this);
    }

    public void initData() {
    }

    private void initListeners() {
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                throw new UnsupportedOperationException("Unsupported operation!");
                // do refactor using Jasypt
                onOk();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOk() {
        String oldPassword = new String(oldPasswordField.getPassword());
        String newPassword = new String(newPasswordField.getPassword());
        String confirmedNewPassword = new String(confirmNewPasswordField.getPassword());

        if (StringUtil.isEmptyOrNullString(newPassword)) {
            showMessage(EMPTY_PASSWORD, JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (!confirmedNewPassword.equals(newPassword)) {
            showMessage(PASSWORDS_NOT_MATCH, JOptionPane.ERROR_MESSAGE);
            return;
        }

        AccountDelegate accountDelegate = new AccountDelegateImpl();
        Account account = AppContext.getInstance().getAccount();
        String login = account.getLogin();
        try {
//            ClientData clientData = new ClientData(login, oldPassword);
//            Authenticator authenticator = Authenticator.getInstance();
//            BigInteger authenticationNumber = accountDelegate.getAuthenticationNumber(login);
//            AuthenticationData authenticationData = authenticator.getAuthenticationData(clientData, authenticationNumber);
////            accountDelegate.login(authenticationData);
//
//            ClientData newClientData = new ClientData(login, newPassword);
//            Point2D publicKey = authenticator.getPublicKey(newClientData);


//            accountDelegate.changePassword(login, publicKey);

            BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
            boolean isValid = passwordEncryptor.checkPassword(oldPassword, account.getPassword());
            if (isValid) {
                accountDelegate.changePassword(login, newPassword);
                showMessage(PASSWORD_SUCCESSFULLY_CHANGED, JOptionPane.INFORMATION_MESSAGE);
            } else {
                showMessage(INCORRECT_LOGIN_OR_PASSWORD, JOptionPane.ERROR_MESSAGE);
            }
            dispose();
        } catch (AccountNotFoundException e) {
            showMessage(LOGIN_NOT_FOUND, JOptionPane.ERROR_MESSAGE);
        } catch (LoginException e) {
            showMessage(INCORRECT_LOGIN_OR_PASSWORD, JOptionPane.ERROR_MESSAGE);
        }
    }

    public void showMessage(String message, int messageType) {
        JOptionPane.showMessageDialog(this, message, TITLE, messageType);
    }

    private void onCancel() {
        dispose();
    }
}
